import { doArea } from '~/api/home'
import type { itemState } from '~/../typings/types/city'
import { store } from '~/stores/app';
const plugin = requirePlugin('WechatSI');
const manager = plugin.getRecordRecognitionManager();
export interface BackItemStatic {
  index: number
  name: string
}

export interface backArrItem {
  index: number
  names: string[]
}
// pages/tabbar/home/components/MusicPop.ts
Component({

  /**
   * 组件的属性列表
   */
  properties: {
    recordState: {
      type: Number,
      value: 0
    },
    content: {
      type: String,
      value: ''
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    allCity: [] as itemState[],
    visible: false as boolean
  },
  lifetimes: {
    created: function () {
      this.initCity()
      this.initSI();
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    matchCommonWords(str1: string, str2: string): BackItemStatic[] {
      const arr: BackItemStatic[] = []
      const arrOne = str1.split('')
      arrOne.forEach((el: string, index: number) => {
        if (el == str2[0] && index !== arrOne.length - 1 && arrOne[index + 1] == str2[1]) {
          arr.push({
            index,
            name: `${el}${arrOne[index + 1]}`
          })
        }
      })
      return arr
    },
    async initCity() {
      const data = await doArea()
      const allData = this.getArr(data, [])
      this.setData({
        allCity: allData
      })
      // this.handSearch('徐州铜山区到北京')
    },
    handSearch(text: string) {
      const backArr = [] as backArrItem[]
      this.data.allCity.forEach((el: itemState) => {
        const labels = el.label.split('-').reverse()
        labels.forEach((item: string, curren: number) => {
          const matchArr = this.matchCommonWords(text, item)
          if (matchArr.length > 0) {
            const names = labels.slice(curren, labels.length).reverse()
            const backArrIndex = backArr.findIndex((ele: backArrItem) => {
              return ele.names[0] == names[0]
            })
            if (backArrIndex >= 0) {
              if (names.length > backArr[backArrIndex].names.length) {
                backArr[backArrIndex] = {
                  names,
                  index: matchArr[0].index,
                }
              }
            } else {
              backArr.push({
                names,
                index: matchArr[0].index,
              })
            }
          }
        })
      })
      backArr.sort((a: backArrItem, b: backArrItem) => a.index - b.index)
      if (backArr.length > 1) {
        store.setSearch({
          star: backArr[0].names.join('-'),
          end: backArr[1].names.join('-')
        })
      } else {
        wx.showToast({
          title: '地址匹配失败',
          icon: 'none',
          duration: 2000,
        });
      }
    },
    getItem(element: itemState, back: itemState[], value: string, label: string) {
      value = value ? value + '-' + element.value : element.value
      label = label ? label + '-' + element.label : element.label
      if (element.children && element.children.length > 0) {
        element.children.forEach((item: itemState) => {
          back = this.getItem(item, back, value, label)
        })
      } else {
        element.label = label
        element.value = value
        back.push(element)
      }
      return back
    },
    getArr(arr: itemState[], back: itemState[]) {
      arr.forEach((element: itemState) => {
        back = this.getItem(element, back, '', '')
      });
      return back
    },
    extractCities(text: string) {
      const citiesRegex = /[a-zA-Z]+\s*[a-zA-Z]*\s*[a-zA-Z]*/g;
      const cities = text.match(citiesRegex) || [];
      return cities;
    },
    initSI() {
      const that = this;
      // 有新的识别内容返回，则会调用此事件
      manager.onRecognize = function (res) {
        console.log(res);
      };
      // 正常开始录音识别时会调用此事件
      manager.onStart = function (res) {
        console.log('成功开始录音识别', res);
        // 开始录音时-抖动一下手机
        wx.vibrateShort({ type: 'medium' });
      };
      // 识别错误事件
      manager.onError = function (res) {
        console.error('error msg', res);
        const tips = {
          '-30003': '说话时间间隔太短，无法识别语音',
          '-30004': '没有听清，请再说一次~',
          '-30011': '上个录音正在识别中，请稍后尝试',
        };
        const retcode = res?.retcode.toString();
        retcode &&
          wx.showToast({
            title: tips[`${retcode}`],
            icon: 'none',
            duration: 2000,
          });
      };
      //识别结束事件
      manager.onStop = function (res) {
        console.log('..............结束录音', res);
        console.log('录音临时文件地址 -->', res.tempFilePath);
        console.log('录音总时长 -->', res.duration, 'ms');
        console.log('文件大小 --> ', res.fileSize, 'B');
        console.log('语音内容 --> ', res.result);
        if (res.result === '') {
          wx.showModal({
            title: '提示',
            content: '没有听清，请再说一次~',
            showCancel: false,
          });
          store.setContent('')
          store.setRecordState(0)
          return;
        }
        var text = res.result;
        store.setContent(text)
        that.handSearch(text)
      };
    },
    // 手指触摸动作-开始录制语音
    touchStart() {
      store.setRecordState(1)
      // 语音识别开始
      manager.start({
        duration: 30000,
        lang: 'zh_CN',
      });
    },
    // 手指触摸动作-结束录制
    touchEnd() {
      store.setRecordState(3)
      // 语音识别结束
      manager.stop();
    },
    open(this: any, nickName: string) {
      this.setData({
        visible: true,
        nickName
      });
      store.setRecordState(0)
      store.setContent('')

    },
    close(this: any) {
      this.setData({
        visible: false
      })
    },
    onVisibleChange(this: any, e: any) {
      if (!e.detail.visible) {
        this.close()
      }
    },
  }
})